const NeedLogin = require('../need_login.js');

module.exports = class extends NeedLogin {
  async indexAction() {
    var ajaxData;
    if(this.isGet) ajaxData = this.get()
    if(this.isPost) ajaxData = this.post()
    // 查询 数据库
    try {
      var articleDb = this.mongoose('mongo/sn_article')
      var _aid = think.objId(ajaxData.aid)
      var findArticle = await articleDb.find({
        _id: _aid
      });
      if (findArticle.length <= 0) {
        return this.json({
          status: -1,
          msg: '文章ID不存在'
        })
      }
      var giveDb = this.mongoose('mongo/sn_article_give')
      var findGive = await giveDb.find({
        uid: ajaxData.uid,
        aid: ajaxData.aid
      })
      var current;
      if (findGive.length > 0) {
        await giveDb.update({
          uid: ajaxData.uid,
          aid: ajaxData.aid
        }, {
          status: findGive[0].status == 1 ? 0 : 1
        })
        current = findGive[0].status == 1 ? 0 : 1
      } else {
        console.log('没有数据新建保存')
        var newGive = new giveDb({
          uid: ajaxData.uid,
          aid: ajaxData.aid
        })
        var a = await newGive.save()
        current = 1
      }
      var findGiveCount = await giveDb.find({
        uid: ajaxData.uid,
        aid: ajaxData.aid,
        status: 1
      }).count()
      await articleDb.update({
        _id: think.objId(ajaxData.uid),
      }, { give: findGiveCount });
      return this.json({
        status: 1,
        current: current,
        count: findGiveCount
      })
    } catch (e) {
      return this.json({
        status: -2,
        msg: e.message
      })
    }
  }
};
